<template>
  <a-tree
    v-if="renderTree"
    v-model="checkedKeys"
    :checkable="checkable"
    :default-expanded-keys="defaultExpandedKeys"
    :auto-expand-parent="autoExpandParent"
    :selected-keys="selectedKeys"
    :tree-data="treeData"
    :replace-fields="replaceFields"
    default-expand-all
    @expand="onExpand"
    @load="onLoad"
  >
    <template slot="custom" slot-scope="item">
      <div
        class="node-title text_ellipsis"
        @click="selectNode(item)"
        @dblclick="previewNode(item)"
        :style="{'width':item.uplodable?'300px':'230px'}"
        style="display: inline-block;"
        :title="item[replaceFields.title]">
        <i
          slot="icon"
          class="icon iconfont text-yellow"
          :class="[item.isOpen?'icon-wenjianjia':'icon-folder',((item.privilege && item.privilege.indexOf('必传')!=-1) || item.required)?'text-red':'']"
          v-if="item.uplodable"></i>
        {{ item[replaceFields.name] || item[replaceFields.title] }}
      </div>
      <span class="custom-handle" v-if="item.uplodable && customHandle.materialDirectory && customHandle.materialDirectory.length">
        <span v-for="(auth,index) in customHandle.materialDirectory" :key="index" v-if="item.materialType == '1' || getOperateAuth(item, auth) || (params.isEdit && auth.name === '上传')">
          <upload :currentNode="item" :project-id="projectId" @uploadSuccess="uploadSuccess" v-if="auth.name === '上传'"></upload>
        </span>
      </span>
      <span class="custom-handle" v-if="item.type === 'file' && customHandle.materialFile && customHandle.materialFile.length">
        <span v-for="(auth,index) in customHandle.materialFile" :key="index" v-if="getOperateAuth(item, auth) || isEdit">
          <a-icon
            :title="auth.name"
            :type="auth.icon"
            :style="{ color: auth.color }"
            class="m-r-xxs cursor-pointer"
            @click="materialHandle(auth, item)">
          </a-icon>
        </span>
      </span>
    </template>
  </a-tree>
</template>

<script>
import Upload from '@c/Upload/Upload'
const customHandle = {
  materialDirectory: [
    {
      name: '上传',
      icon: 'upload',
      cb: 'upload'
    }
  ],
  materialFile: [
    {
      name: '浏览',
      icon: 'eye',
      cb: 'preView',
      color: '#3387EA'
    },
    {
      name: '下载',
      icon: 'download',
      cb: 'download',
      color: '#6DD400'
    },
    {
      name: '删除',
      icon: 'delete',
      cb: 'remove',
      color: 'red'
    }
  ]
}
export default {
  name: 'DistTree',
  data () {
    return {
      renderTree: false,
      expandedKeys: [],
      autoExpandParent: false,
      checkedKeys: [],
      selectedKeys: [],
      defaultExpandedKeys: [],
      query: this._.cloneDeep(this.$route.query),
      params: this._.cloneDeep(this.$route.params),
      customHandle: {},
      replaceFields: {
        children: 'children',
        name: 'nick',
        title: 'name',
        key: 'id'
      }
    }
  },
  props: {
    treeId: {
      type: String,
      default: () => {
        return 'distTree_' + Date.parse(new Date())
      }
    },
    checkable: {
      type: Boolean,
      default: () => false
    },
    treeData: {
      type: Array,
      default: () => {
        return []
      }
    },
    defaultExpandAll: {
      type: Boolean,
      default: () => false
    },
    select: {
      type: Function,
      default: () => {
        return () => {}
      }
    },
    load: {
      type: Function,
      default: () => {
        return () => {}
      }
    },
    check: {
      type: Function,
      default: () => {
        return () => {}
      }
    },
    projectId: {
      type: Number
    }
  },
  components: { Upload },
  created () {
  },
  mounted () {
    this.initMaterialAuth()
  },
  computed: {
    getOperateAuth () {
      return (item, btn) => {
        if (this.query.taskId && parseInt(this.query.taskId) > 0) {
          return item.privilege ? item.privilege.split(',').includes(btn.name) : false
        }
        return ['浏览', '下载'].includes(btn.name)
      }
    }
  },
  methods: {
    onExpand (expandedKeys, expanded) {
      // console.log('onExpand', expandedKeys)
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
      this.checkNodeIsOpen(this.treeData, expanded.node.eventKey, expanded.expanded)
    },
    onCheck (checkedKeys) {
      // console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect (selectedKeys, info) {
      // console.log('onSelect', info)
      this.selectedKeys = selectedKeys
      this.$emit('input', selectedKeys)
      this.$emit('select', selectedKeys)
      if (typeof this.select === 'function') {
        this.select(selectedKeys)
      }
    },
    onLoad () {
      this.$emit('load')
    },
    initExpandKeys (treeData, parentKey) {
      treeData.forEach(item => {
        item.parentKey = parentKey
        item.scopedSlots = { title: 'custom' }
        item.isOpen = true
        if (item.open && item.open === true) {
          this.defaultExpandedKeys.push(item[this.replaceFields.key])
        }
        if (item.children) {
          this.initExpandKeys(item.children, item[this.replaceFields.key])
        }
      })
    },
    checkNodeIsOpen (treeData, nodeKey, expanded) {
      treeData.forEach(item => {
        if (item[this.replaceFields.key] == nodeKey) {
          item.isOpen = expanded
        }
        if (item.children) {
          this.checkNodeIsOpen(item.children, nodeKey, expanded)
        }
      })
    },
    materialHandle (handle, node) {
      const data = {
        handle: handle.cb,
        file: node,
        treeId: this.treeId
      }
      this.Event.$emit('materialHandle', data)
    },
    uploadSuccess (data) {
      // 刷新右侧材料树
      data.treeId = this.treeId
      this.Event.$emit('FORMRIGHT_MATERIAL_REFRESH', { projectId: this.projectId })
      this.Event.$emit('_REFRESH_MATERIAL_MANAGER_', { projectId: this.projectId })
    },
    selectNode (item) {
      console.log('selectNode', item)
      if (item.type === 'file') {
        const data = {
          handle: 'preView',
          file: item,
          treeId: this.treeId
        }
        this.Event.$emit('materialHandle', data)
      }
    },

    previewNode (item) {
      if (item.type === 'file') {
        const data = {
          handle: 'preView',
          file: item,
          treeId: this.treeId
        }
        this.Event.$emit('materialHandle', data)
      }
    },
    initMaterialAuth () {
      if (this.query.taskId || this.params.isEdit) {
        this.customHandle = customHandle
      } else {
        this.customHandle = {
          materialFile: [
            {
              name: '浏览',
              icon: 'eye',
              cb: 'preView',
              color: '#3387EA'
            },
            {
              name: '下载',
              icon: 'download',
              cb: 'download',
              color: '#6DD400'
            }
          ]
        }
      }
      console.log(this.customHandle)
    }
  },
  watch: {
    checkedKeys (val) {
      console.log('onCheck', val)
    },
    treeData (val) {
      if (val.length > 0) {
        this.renderTree = true
        this.initExpandKeys(this.treeData, null)
      }
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .ant-tree-treenode-switcher-open{
  position: relative;
}
/deep/ .ant-tree-treenode-switcher-close{
  position: relative;
}
/deep/ .ant-tree-node-content-wrapper:hover{
  background-color: white;
}
.custom-handle {
  position: absolute;
  right: 10px;
}
.text_ellipsis{
  width:300px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
}
.ml5{
  margin-left: 5px;
}
.text-red{
  color: red !important;
}
</style>
